<template>
  <div>
    <!--引用top提示信息-->
    <Card class="m-2" title="表单表格-集成" :headStyle="{ fontSize: '20px' }">
      <li>使用watch函数监听</li>
      <li>自定义查询按钮文本 + 自定义说明 + 自定义右侧toolbar</li>
    </Card>
    <!--引用表格-->
    <BasicTable @register="registerTable" title="基础示例">
      <template #tableTop>
        <div class="weight-hint">
          <p class="hint_title">说明</p>
          <ul>
            <li>若方案不参与权重计算，请将该方案权重设置为0（或不填）</li>
            <li>若不设置小数点位数，默认小数点位数为2</li>
            <li v-if="isShowHint" style="color: red">当前方案（方案启用并且参与计算）的权重之和不等于100,建议重新维护权重数据！</li>
          </ul>
        </div>
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleParent"> 父子组件传值 </a-button>
        <a-button type="default" danger> 危险 </a-button>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <testParentSunModal @register="registerTestParentSunModal" @success="handleTestParentSunSuccess" />
  </div>
</template>

<script lang="ts" name="emp-est01" setup>
import { ref, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';
import { Card, Row, Col, Spin } from 'ant-design-vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import testParentSunModal from './components/testParentSunModal.vue';
import { columns, searchFormSchemaTest } from './data';
import { list, deleteOne, getImportUrl, getExportUrl } from './api';
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage(); // 解构

const queryParam = reactive<any>({});
import { mapTableTotalSummary } from '/@/utils/common/compUtils';
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

//注册model
const [registerTestParentSunModal, { openModal: openTestParentSunModal }] = useModal();
//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: 'test02表',
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,        //显示行号
    showActionColumn: true,      //显示操作列
    immediate: true,             //自动请求
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchemaTest,
      compact: true,                //紧凑的
      showResetButton: true,
      showSubmitButton: true,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,          //高级按钮，重置后面的收起、展开
      fieldMapToNumber: [],
      fieldMapToTime: [],             //日期框转换 
      // fieldMapToTime: [['sendTime', ['beginDate', 'endDate'], 'YYYY-MM-DD']],  //日期框转换 
      submitButtonOptions: {          //自定义确定按钮文本
        text: 'go',
      },
      disabled: false,
    },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    showSummary: false,  // 显示底部合计
    striped: true,      //斑马纹
    // summaryFunc: onSummary,// 底部合计计算方法
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: 'test02表',
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});

const [registerTable, { reload, getForm }, { selectedRowKeys }] = tableContext;

// 页面参数变量
const startEdit = ref<boolean>(false);
const isShowHint = ref<boolean>(true);
const orgName = ref(userStore.getOrgName);

//监控
watch(
  orgName,
  (v) => {
    $message.info('orgName改变了......' + v);
  }
);

// 默认执行一次
onMounted(async () => {
  await initTeamSelect();
});

/**
 * 初始化下拉框
 */
async function initTeamSelect() {
  let form = getForm();
  form.updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          console.log('切换了：',e);
          orgName.value = i?.label;
          handleSuccess();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
}

/**
 * 测试事件
 */
function handleParent() {
  // $message.info('后面为测试按钮');
  openTestParentSunModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 新增事件
 */
function handleAdd() {
}

/**
 * 测试父子组件传值
 */
function handleTestParentSunSuccess(params) {
  $message.info('子页面输入的值为：' + params);
}

/**
 * 编辑事件
 */
 function handleEdit(record) {
  $message.info('编辑了......' + record.id);
}
/**
 * 删除事件
 */
 async function handleDelete(record) {
  await deleteOne({ id: record.id });
  handleSuccess();
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 提交事件
 */
function handleSubmit() {
  let form = getForm();
  let formData = form.getFieldsValue();
  let params = Object.assign({}, formData);
  console.log('表单数据', params);
  reload({ searchInfo: params });
}

/**
 * 底部合计
 */
function onSummary(tableData: Recordable[]) {
  // 可用工具方法自动计算合计
  const totals = mapTableTotalSummary(tableData, ['displayOrder']);
  return [
    totals,
    {
      // _row: '平均',
      _index: '平均',
      displayOrder: (totals.displayOrder / tableData.length).toFixed(2),// 计算平均值
    },
  ];
}
/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      icon: 'clarity:note-edit-line',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      icon: 'ant-design:delete-outlined',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}

.m-4 {
  background-color: #fff;
  padding-top: 20px;
  margin: 0px;
}
</style>